package com.gomo;

import java.util.ArrayList;
import org.ksoap2.serialization.SoapObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.gomo.R;
import com.gomo.adapter.CcAdapter;
import com.gomo.entity.Cc;
import com.gomo.entity.Country;
import com.gomo.entity.User;

public class SignupActivity extends Activity {

	private EditText txtSignupName;
	private EditText txtSignupCNIC;
	private EditText txtSignupPassport;
	private EditText txtSignupAddress;
	private EditText txtSignupCity;
	private EditText txtSignupState;
	private Spinner spnrSignupCountry;
	private EditText txtSignupContact;
	private EditText txtSignupEmail;
	private Button btnSingnupSubmit;
	AlertDialog alertDialog;

	// private String _strCountryId = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signup);
		setUI();
	}

	public void buttonSignupSubmitClick(View view) {
		// String message = _strCountryId;
		// String message = spnrSignupCountry.get;

		/*
		 * String selectedVal = getResources().getStringArray(
		 * R.array.country_values)[spnrSignupCountry
		 * .getSelectedItemPosition()]; GlobalService.MessageBox(selectedVal,
		 * this);
		 */

		if (isValidate()) {
			new ParseXmlTaskCreateUser().execute();
		}
	}

	private void setUI() {
		txtSignupName = (EditText) findViewById(R.id.signup_text_name);
		txtSignupCNIC = (EditText) findViewById(R.id.signup_text_cnic);
		txtSignupPassport = (EditText) findViewById(R.id.signup_text_passport);
		txtSignupAddress = (EditText) findViewById(R.id.signup_text_address);
		txtSignupCity = (EditText) findViewById(R.id.signup_text_city);
		txtSignupState = (EditText) findViewById(R.id.signup_text_province);

		spnrSignupCountry = (Spinner) findViewById(R.id.signup_spinner_country);

		txtSignupContact = (EditText) findViewById(R.id.signup_text_contact);
		txtSignupEmail = (EditText) findViewById(R.id.signup_text_email);
		btnSingnupSubmit = (Button) findViewById(R.id.signup_button_submit);
		createDialogMessage();
		new ParseXmlTaskGetCountryList().execute();
	}

	private boolean isValidate() {
		if (!GlobalService.isOnline(this)) {
			GlobalService.MessageBox("No or limited internet connection", this);
			return false;
		}
		return true;
	}

	private void createDialogMessage() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("").setCancelable(false)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		alertDialog = builder.create();
	}

	private String processServiceCreateUser() {
		SoapService ss = new SoapService();

		String soap_method_name = getString(R.string.method_user_create);
		String soap_namespace = getString(R.string.service_namespace);
		String soap_url = getString(R.string.service_url);
		String soap_action = soap_namespace + soap_method_name;
		String android_id = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);

		SoapObject soap_object_request = new SoapObject(soap_namespace,
				soap_method_name);

		soap_object_request.addProperty("Name", txtSignupName.getText()
				.toString());
		soap_object_request.addProperty("CNIC", txtSignupCNIC.getText()
				.toString());
		soap_object_request.addProperty("PassportNo", txtSignupPassport
				.getText().toString());
		soap_object_request.addProperty("Address", txtSignupAddress.getText()
				.toString());
		soap_object_request.addProperty("City", txtSignupCity.getText()
				.toString());
		soap_object_request.addProperty("StateProvince", txtSignupState
				.getText().toString());
		soap_object_request.addProperty("Country", spnrSignupCountry
				.getSelectedItem().toString());
		soap_object_request.addProperty("ContactNo", txtSignupContact.getText()
				.toString());
		soap_object_request.addProperty("EmailId", txtSignupEmail.getText()
				.toString());
		soap_object_request.addProperty("DeviceId", android_id);
		soap_object_request.addProperty("DeviceType", "2");

		SoapObject soap_object_response = ss.parseWebService(soap_action,
				soap_url, soap_object_request);
		SoapObject recordsArray = (SoapObject) soap_object_response
				.getProperty(0);
		String soapresultid = recordsArray.getProperty("ID").toString();
		String soapresultmsg = recordsArray.getProperty("Message").toString();
		return soapresultid + "|" + soapresultmsg;
	}

	class ParseXmlTaskCreateUser extends AsyncTask<Void, Void, String> {
		private final ProgressDialog dialog = new ProgressDialog(
				SignupActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Signing up...");
			this.dialog.show();
		}

		protected String doInBackground(Void... unused) {
			return processServiceCreateUser();
		}

		protected void onPostExecute(String soapresultmsg) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();

			String[] arrString = GlobalService.splitString(soapresultmsg, "|");
			String id = arrString[0];
			String message = arrString[1];

			alertDialog.setMessage(message);
			alertDialog.show();

			if (!id.equalsIgnoreCase("0")) {
				btnSingnupSubmit.setEnabled(false);
			}
		}
	}

	private ArrayList<Country> processServiceGetCountryList() {
		SoapService ss = new SoapService();

		String soap_method_name = getString(R.string.method_country_get);
		String soap_namespace = getString(R.string.service_namespace);
		String soap_url = getString(R.string.service_url);
		String soap_action = soap_namespace + soap_method_name;
		String android_id = Secure.getString(getBaseContext()
				.getContentResolver(), Secure.ANDROID_ID);

		SoapObject soap_object_request = new SoapObject(soap_namespace,
				soap_method_name);

		SoapObject soap_object_response = ss.parseWebService(soap_action,
				soap_url, soap_object_request);

		SoapObject recordsArray = (SoapObject) soap_object_response
				.getProperty(0);
		int recordCount = recordsArray.getPropertyCount();
		ArrayList<Country> theArrayList = new ArrayList<Country>();
		try {
			for (int i = 0; i < recordCount; i++) {
				Country item = new Country();
				Ksoap2ResultParser.parseBusinessObject(recordsArray
						.getProperty(i).toString(), item);
				theArrayList.add(item);
			}
		}

		catch (NumberFormatException e) {
			// e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// e.printStackTrace();
		} catch (IllegalAccessException e) {
			// e.printStackTrace();
		} catch (InstantiationException e) {
			// e.printStackTrace();
		}
		return theArrayList;
	}

	class ParseXmlTaskGetCountryList extends
			AsyncTask<Void, Void, ArrayList<Country>> {
		private final ProgressDialog dialog = new ProgressDialog(
				SignupActivity.this);

		protected void onPreExecute() {
			this.dialog.setMessage("Getting country list...");
			this.dialog.show();
		}

		protected ArrayList<Country> doInBackground(Void... unused) {
			return processServiceGetCountryList();
		}

		protected void onPostExecute(ArrayList<Country> cclist) {
			if (this.dialog.isShowing())
				this.dialog.dismiss();
			MyAdapter adapter = new MyAdapter(cclist);
			spnrSignupCountry.setAdapter(adapter);
		}
	}

	private class MyAdapter implements SpinnerAdapter {

		/**
		 * The internal data (the ArrayList with the Objects).
		 */
		ArrayList<Country> data;

		public MyAdapter(ArrayList<Country> data) {
			this.data = data;
		}

		/**
		 * Returns the Size of the ArrayList
		 */
		public int getCount() {
			return data.size();
		}

		/**
		 * Returns one Element of the ArrayList at the specified position.
		 */
		public Object getItem(int position) {
			return data.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public int getItemViewType(int position) {
			return android.R.layout.simple_spinner_dropdown_item;
		}

		/**
		 * Returns the View that is shown when a element was selected.
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView v = new TextView(getApplicationContext());
			v.setTextColor(Color.BLACK);
			v.setText(data.get(position).getCountryName());
			return v;
		}

		public int getViewTypeCount() {
			return 1;
		}

		public boolean hasStableIds() {
			return false;
		}

		public boolean isEmpty() {
			return false;
		}

		public void registerDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

		public void unregisterDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

		/**
		 * The Views which are shown in when the arrow is clicked (In this case,
		 * I used the same as for the "getView"-method.
		 */
		public View getDropDownView(int position, View convertView,
				ViewGroup parent) {
			return this.getView(position, convertView, parent);
		}

	}

}